package com.lixueju.security.box.web.authentication;

import com.alibaba.fastjson.JSONObject;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * @author lixueju
 * @since 2019/11/12 17:58
 **/
public class SecurityBoxAuthenticationProvider implements AuthenticationProvider {
    private UserDetailsService userDetailsService;

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#
     * authenticate(org.springframework.security.core.Authentication)
     */
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

        SecurityBoxAuthenticationToken authenticationToken = (SecurityBoxAuthenticationToken) authentication;
        authenticationToken.getPrincipal();
        JSONObject principal = JSONObject.parseObject(JSONObject.toJSONString(authenticationToken.getPrincipal()));
        principal.remove("id");
        UserJwt user = (UserJwt) userDetailsService.loadUserByUsername(principal.toJSONString());

        if (user == null) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
        }

        SecurityBoxAuthenticationToken authenticationResult = new SecurityBoxAuthenticationToken(user, user.getAuthorities());

        authenticationResult.setDetails(authenticationToken.getDetails());

        return authenticationResult;
    }

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.authentication.AuthenticationProvider#
     * supports(java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> authentication) {
        return SecurityBoxAuthenticationToken.class.isAssignableFrom(authentication);
    }

    public UserDetailsService getUserDetailsService() {
        return userDetailsService;
    }

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }
}
